package com.easydb.client;

import java.util.ArrayList;

import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;

// SmartGWT stuff
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ListGridEditEvent;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.RowEndEditAction;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.HTMLFlow;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.CheckboxItem;
import com.smartgwt.client.widgets.form.fields.RadioGroupItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import com.smartgwt.client.widgets.grid.events.ChangedEvent;
import com.smartgwt.client.widgets.grid.events.ChangedHandler;
import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class EasyDB implements EntryPoint {

	
	private final TabSet wizardTab =new TabSet();
	
	private Tab tab1 =new Tab("Step1");
	private Tab tab2 =new Tab("Step2");
	private Tab tab3 =new Tab("Step3");
	private Tab tab4 =new Tab("Step4");
	private DynamicForm form1=new DynamicForm(); 
    private RadioGroupItem formTypes = new RadioGroupItem("formType");

    
    private VLayout mainLayout =new VLayout();
    private VLayout step1 =new VLayout();
    private VLayout step2 =new VLayout();
    
    private ListGrid fieldsList =new ListGrid();
    private VLayout tab2Content = new VLayout();
    private DynamicForm propsList =new DynamicForm();
    private ListGrid props =new ListGrid();

    
    // field properties button creation
	// fields that are the same for all field types
    private TextItem fieldLen=new TextItem("len","Field lenght");
    private TextItem validation=new TextItem("validation","Validation rule");

    private TextItem dateFormat=new TextItem("format","date format");

    private SelectItem lookupType=new SelectItem ("Lookup type");
    private SelectItem lookupTable=new SelectItem ("Lookup table");
    private SelectItem fieldToShow=new SelectItem ("Table Field");
    private TextItem lookupData=new TextItem("lookupData","LookupData");

    
    
    private IButton addField = new IButton("Add field");
    private IButton remField = new IButton("Remove");
    private HLayout fieldButtons=new HLayout();
    
    private HLayout buttons=new HLayout();
    private Button next=new Button("Next");
    private Button finish=new Button("Finish");
    private Button previous=new Button("Previous");
    
    
	public void onModuleLoad() {

		/*
		 * Veidojam Formu veidosanas wizardu
		 */
		// TODO izveidot normaalu izskatu lapai
		// TODO paarlikt uz citu klasi
		
		initStep1();

		Canvas tab1Content = new Canvas();
		tab1Content.addChild(step1);
		tab1.setPane(tab1Content);

		wizardTab.addTab(tab1);
		wizardTab.addTab(tab2);
		wizardTab.setWidth100();
		//wizardTab.setHeight100();

		mainLayout.addMember(wizardTab);

		initStep2();
		setWizardButtons();

		mainLayout.addMember(buttons);
		mainLayout.setWidth100();
		mainLayout.setHeight100();

		mainLayout.draw();
		//RootPanel.get("stockList").add(wizardTab);
		
	}

	private void setWizardButtons() {
		next.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				int currTab=wizardTab.getSelectedTabNumber();
				if (currTab<wizardTab.getNumTabs()-1) wizardTab.selectTab(currTab+1 );
			}
		});

		previous.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				int currTab=wizardTab.getSelectedTabNumber();
				if (currTab>0) wizardTab.selectTab(wizardTab.getSelectedTabNumber()-1);
			}
		});

		finish.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				wizardTab.selectTab(0);
			}
		});
		
		buttons.addMember(previous);
		buttons.addMember(next);
		buttons.addMember(finish);
		buttons.setAlign(Alignment.RIGHT );

	}
	
	private boolean initStep1(){

		final String welcome="<h4>Welcome to <b>EasyDb</b>. Please choose form name and type</h4>";
		final HTMLFlow htmlFlow = new HTMLFlow();
        htmlFlow.setTop(40);
        htmlFlow.setWidth(600);
        htmlFlow.setStyleName("exampleTextBlock");
		htmlFlow.setContents(welcome);
		//htmlFlow.setMargin(10);
		step1.addMember(htmlFlow);
		
		// TODO format form to look better, 
		TextItem projName=new TextItem("name","Project name");
		projName.setWrapTitle(false);

		//projName.setWidth(400);
		TextItem projType=new TextItem("type","Project type");

		formTypes.setTitle("Form type");
		formTypes.setVertical(false);
		formTypes.setValueMap("Single record", "Grid");
		form1.setFields(projName,projType,formTypes);
		
		step1.addMember(form1);

		// TODO error check and validation
		
		return true;
	}
	
	/**
	 * initialises all widgets that can be seen on step 2
	 * @return page generated successfully/failure
	 */
	private boolean initStep2(){
		//fieldsList
        setupFieldList();
        
		//lookupType.disable();
		//lookupTable.disable();
        createFieldListData();

        step2.addMember(fieldsList);
		step2.setWidth100();
		step2.setHeight100();

		//setFieldProperties("char");
		step2.addMember(propsList);
        
		//Setting up add/remove buttons
        addField.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				fieldsList.startEditingNew();				
			}
		});
		
        remField.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				ListGridRecord recNo=fieldsList.getSelectedRecord();
				if (recNo!=null){
					fieldsList.removeData(recNo);
				}
			}
		});
        
        fieldButtons.addMember(addField);        
        fieldButtons.addMember(remField);        
        step2.addMember(fieldButtons);

        tab2Content.addChild(step2);
		tab2.setPane(tab2Content);
        
		return true;
	}

	/**
	 * creates field grid look and data
	 */
	private void setupFieldList() {
		ListGridField itemName = new ListGridField("name", 100);
        itemName.setType(ListGridFieldType.TEXT);
        ListGridField itemType = new ListGridField("type", 100);
        itemType.setType(ListGridFieldType.TEXT);
        ListGridField mandatory = new ListGridField("mandatory", 50);
        mandatory.setType(ListGridFieldType.BOOLEAN );
        ListGridField len = new ListGridField("lenght", 50);
        len.setType(ListGridFieldType.TEXT);
        ListGridField description = new ListGridField("description", 150);
        description.setType(ListGridFieldType.TEXT);
        itemType.setValueMap("char", "int", "date","lookup");
        
        itemType.addChangedHandler(new ChangedHandler() {
			public void onChanged(ChangedEvent event) {
            	String val = event.getValue().toString(); 
            	setFieldProperties(val);
			}
		});
        
        fieldsList.setFields(itemName, itemType,mandatory,len, description);
        fieldsList.addRecordClickHandler(new RecordClickHandler() {
            public void onRecordClick(RecordClickEvent event) {
            	Record record=event.getRecord();
            	setFieldProperties(record.getAttribute("type").toString());
            }
		});
        
        
        
        fieldsList.setAlternateRecordStyles(true);
        fieldsList.setCanEdit(true);
        //fieldsList.setModalEditing(true);
        fieldsList.setEditEvent(ListGridEditEvent.CLICK);
        fieldsList.setListEndEditAction(RowEndEditAction.NEXT);

	}

	private void createFieldListData() {
		ListGridRecord rec1=new ListGridRecord();
        rec1.setAttribute("name", "field1");
        rec1.setAttribute("type", "char");
        rec1.setAttribute("lenght", "10");
        rec1.setAttribute("mandatory", true);
        rec1.setAttribute("description", "simple field");
        fieldsList.addData(rec1);

        ListGridRecord rec2=new ListGridRecord();
        rec2.setAttribute("name", "field2");
        rec2.setAttribute("type", "date");
        rec2.setAttribute("lenght", "10");
        rec2.setAttribute("mandatory", true);
        rec2.setAttribute("description", "simple field");
        fieldsList.addData(rec2);
	}
	
	
	/**
	 * Generates field properties form according to field type
	 * @param fieldType
	 * @return success/failure
	 */
	private boolean setFieldProperties(String fieldType){
		
		// TODO some err check
		// need better check for fieldTypes is there any ID for select values
		if (fieldType.equals("char")) propsList.setFields(fieldLen,validation);
		if (fieldType.equals("int")) propsList.setFields(fieldLen,validation);
		if (fieldType.equals("date")) propsList.setFields(fieldLen,validation,dateFormat);
		if (fieldType.equals("lookup")) setLookup();
		
		return true;
	}

	/**
	 * Sets form to enter properties for lookup field.
	 * Users can input their own value list, or get value list from other table
	 * @return succeess/fail
	 */
	private boolean setLookup(){
		propsList.setFields(lookupType,lookupTable,lookupData);
		// TODO change for real data
		lookupType.setValueMap("local", "table");
		lookupTable.setValueMap("table1", "tabl2", "table2");
		lookupData.hide();
		lookupTable.hide();

		
		lookupType.addChangedHandler(new com.smartgwt.client.widgets.form.fields.events.ChangedHandler() {
			public void onChanged(
					com.smartgwt.client.widgets.form.fields.events.ChangedEvent event) {
				
				if (event.getValue().toString().equals("local")){
					lookupTable.hide();
					lookupTable.disable();
					lookupData.show();

				}
				else {
					lookupTable.show();
					lookupData.hide();
					lookupTable.enable();
				}
			}
		});
		
		return true;
	}
		
	
	
	
	
}


